package com.jeomo.masterdata.starter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.constant.SearchParam;
import com.jeomo.common.core.dto.PageQueryDto;
import com.jeomo.common.core.dto.PageResponseDto;
import com.jeomo.common.util.RedisUtil;
import com.jeomo.masterdata.starter.constant.MemberRedisKey;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.entity.Level;
import com.jeomo.masterdata.starter.entity.Merchant;
import com.jeomo.masterdata.starter.mapper.GoodsMapper;
import com.jeomo.masterdata.starter.mapper.MerchantMapper;
import com.jeomo.masterdata.starter.service.IMerchantService;
import com.jeomo.masterdata.starter.util.CommonUtil;
import com.jeomo.shiro.util.LoginSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <h3>jeomo</h3>
 * <p></p>
 *
 * @author : 崔贺
 * @date : 2020-08-28 13:47
 **/
@Service
public class MerchantServiceImpl extends BaseServiceImpl<MerchantMapper, Merchant>
        implements IMerchantService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MerchantMapper merchantMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private RedisUtil redisUtil;//缓存

    private final String CACHE_KEY = MemberRedisKey.MEM_MERCHANT_HASH_KEY;

    @Override
    public int create(Merchant merchant) {
        String currentOrgCode = LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode();
        merchant.setOrgCode(currentOrgCode);
        String recentlyCode = merchantMapper.queryRecentlyCode(currentOrgCode);
        String code = CommonUtil.spliceCode(currentOrgCode, recentlyCode);
        merchant.setCode(code);
        int insert =  merchantMapper.insert(merchant);
        redisUtil.hset(CACHE_KEY, merchant.getCode(), merchant.getName());
        return insert;

    }

    @Override
    public Boolean removeMerchant(String code) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_code", code);
        List<Goods> goods = goodsMapper.selectList(queryWrapper);
        if (goods.isEmpty()) {
            merchantMapper.deleteById(code);
            redisUtil.hdel(CACHE_KEY,code);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Map<String, String> queryCache() {

        Map<Object, Object> cacheMap = redisUtil.hmget(CACHE_KEY);
        if (!cacheMap.isEmpty()) {
            return patchData(cacheMap);
        }
        refreshCache();
        cacheMap = redisUtil.hmget(CACHE_KEY);
        return patchData(cacheMap);
    }

    public Map<String, String> patchData(Map<Object, Object> cacheMap) {
        HashMap<String, String> levelMap = new HashMap<>(8);
        Set<Object> objects = cacheMap.keySet();
        for (Object object : objects) {
            levelMap.put(object.toString(), cacheMap.get(object).toString());
        }
        return levelMap;
    }

    /**
     * 刷新缓存:删除缓存key,读取数据库,加入缓存
     */
    public void refreshCache() {
        redisUtil.del(CACHE_KEY);
        List<Merchant> merchants = merchantMapper.selectList(null);
        for (Merchant merchant : merchants) {
            redisUtil.hset(CACHE_KEY, merchant.getCode(), merchant.getName());
        }
    }

    @PostConstruct
    public void init() {
        logger.info("Redis缓存初始化:[商户]基础数据");
        refreshCache();
    }

    @Override
    public List<Merchant> selectMerchantByTobCode(String tobCode,String orgCode) {
        return merchantMapper.selectMerchantByTobCode(tobCode,orgCode);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMerchantAndGoodsFlag(String merchantCode, boolean flag) {
        UpdateWrapper<Merchant> merchantUpdateWrapper = new UpdateWrapper<>();
        merchantUpdateWrapper.set("start_flag", flag);
        merchantUpdateWrapper.eq("code", merchantCode);
        int merchant = merchantMapper.update(null, merchantUpdateWrapper);
        UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
        goodsUpdateWrapper.set("start_flag", flag);
        goodsUpdateWrapper.eq("merchant_code", merchantCode);
        int goods = goodsMapper.update(null, goodsUpdateWrapper);
        return merchant + goods;
    }

    @Override
    public PageResponseDto pageSearch(PageQueryDto dto) {
        //1. 处理查询参数
        Map<String, Object> searchParams = dto.getSearchParams();
        searchParams.put(SearchParam.SEARCH_EQ + "org_code", LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode());
        return super.pageSearch(dto);
    }
}
